package org.anderes.playground.csv;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;

public class CsvFileHandling {

	private Map<String, String> map = new HashMap<String, String>();
	
	@Before
	public void setUp() {
		generateTestData();
	}

	private void generateTestData() {
		map.put("Start", "12345");
		map.put("West", "öäüèéà");
		map.put("End", "homedrive");
	}
	
	@Test
	public void writeCsvFile() {
		File csvFile = null;
		try {
			csvFile = File.createTempFile("csvFile_", ".csv");
		} catch (IOException e) {
			fail(e.getMessage());
		}
		CsvFileHandler handler = CsvFileHandler.build(csvFile);
		try {
			handler.writeMap(map);
		} catch (Exception e) {
			fail(e.getMessage());
		}
		assertThat(String.format("File '%1$s' existiert nicht!", csvFile.getAbsolutePath()), csvFile.exists(), is(true));
		assertThat("Filegrösse ist falsch.", csvFile.length(), is(equalTo(59L)));
	}

	@Test
	public void readCsvFile() {
		CsvFileHandler handler = CsvFileHandler.build(getTestFile());
		Map<String, String> map = null;
		try {
			map = handler.readCsvFile();
		} catch (Exception e) {
			fail(e.getMessage());
		}
		assertNotNull("Die Map darf nicht null sein", map);
		assertThat("Falsche Grösse der Map", map.size(), is(equalTo(3)));
		assertThat(map, is(equalTo(this.map)));
	}
		
	private File getTestFile() {
		String name = "org/anderes/playground/csv/csvFile.csv";
		URL url = Thread.currentThread().getContextClassLoader().getResource(name);
		assertNotNull(String.format("Die Resource '%s' existiert nicht.", name), url);
		File csvFile = new File(url.getFile());
		assertThat(String.format("File '%1$s' existiert nicht!", csvFile.getAbsolutePath()), csvFile.exists(), is(true));
		return csvFile;
	}
}
